//
//  MBSpaceSetUpNewViewController.m
//  MiBaoTu
//
//  Created by admin on 16/9/22.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBSpaceSetUpNewViewController.h"
#import "MBSpaceMusicClassViewController.h"
#import "MBLoginController.h"

@interface MBSpaceSetUpNewViewController ()<UITextFieldDelegate> {
    UIView                  *bgView;
    UITextField             *_textField;
    UILabel                 *_showLb;
}

@end

@implementation MBSpaceSetUpNewViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    if (ISIPAD) {
//        [self onUpdateUIForView:self.orientation];
//    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setTitleView:@"新建分类"];
    
    UIButton *backbt = [UIButton buttonWithType:UIButtonTypeCustom];
    backbt.frame = CGRectMake(0, 0, 60, 30);
    [backbt setTitle:@"取消" forState:UIControlStateNormal];
    [backbt setTitle:@"取消" forState:UIControlStateHighlighted];
    [backbt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backbt setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    backbt.titleLabel.font = [UIFont systemFontOfSize:13.f];
    [backbt setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 30)];
    [backbt addTarget:self action:@selector(onSelectItemForBack) forControlEvents:UIControlEventTouchUpInside];
    [self setLeftBarItem:backbt];
    
    UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
    bt.frame = CGRectMake(0, 0, 60, 30);
    [bt setTitle:@"完成" forState:UIControlStateNormal];
    [bt setTitle:@"完成" forState:UIControlStateHighlighted];
    [bt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [bt setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    bt.titleLabel.font = [UIFont systemFontOfSize:13.f];
    [bt setTitleEdgeInsets:UIEdgeInsetsMake(0, 30, 0, 0)];
    [bt addTarget:self action:@selector(onSelectItemForWork) forControlEvents:UIControlEventTouchUpInside];
    [self setRightBarItems:bt];
    
    [self onCreateUI];
}

- (void)onCreateUI
{
    bgView = [[UIView alloc]initWithFrame:CGRectMake(25*PERCEN,(ISPortrait?NAV_HEIGHT+20*PERCEN:44+20*PERCEN), SCREEN_WIDTH-50*PERCEN, 80*PERCEN)];
    if (ISIPAD) {
        bgView.top = NAV_HEIGHT+20*PERCEN;
    }
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.cornerRadius = 5.0f;
    bgView.layer.masksToBounds = YES;
    [self.view addSubview:bgView];
    if (ISIPAD) {
        bgView.width = self.view.width-50*PERCEN;
    }
    
    _textField = [[UITextField alloc]initWithFrame:CGRectMake(20*PERCEN, (80*PERCEN-30)/2., bgView.width-40*PERCEN, 30)];
    _textField.placeholder = @"请输入新分类的名称，20字以内";
    _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textField.borderStyle = UITextBorderStyleNone;
    _textField.delegate = self;
    _textField.font = [UIFont systemFontOfSize:13.];
    _textField.attributedPlaceholder = [[NSAttributedString alloc]initWithString:_textField.placeholder attributes:@{NSForegroundColorAttributeName: UIColorFromHex(0x999999),NSFontAttributeName:_textField.font}];
    [bgView addSubview:_textField];
    
    _showLb = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-25*PERCEN-120, bgView.bottom, 120, 20)];
    _showLb.backgroundColor = [UIColor clearColor];
    _showLb.textAlignment = NSTextAlignmentRight;
    _showLb.textColor = UIColorFromHex(0x9999999);
    _showLb.font = [UIFont systemFontOfSize:11.f];
    _showLb.text = @"0/20";
    [self.view addSubview:_showLb];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onTapForHideAction)];
    [self.view addGestureRecognizer:tap];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Actions
//完成
- (void)onSelectItemForWork
{
    UserModel *model = [UserManager standerDefult].userModel;
    if (!model.UserID) {
        MBLoginController *registerLastVC = [[MBLoginController alloc] init];
        registerLastVC.formBaseViewCtrl = NSStringFromClass([self class]);
        [self.navigationController pushViewController:registerLastVC animated:YES];
        return;
    }
    
    if (_textField.text.length > 0 && model) {
        //创建成功存入数据库，跳到下一步
        
        [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:SPACE_CREATEALBUM_URL_PATH,model.UserID,_textField.text] view:nil success:^(NSDictionary * json) {
            if ([json[@"ret_code"] integerValue]==0) {
                //不存在，开始插入
                NSString *CateID = [NSString stringWithFormat:@"%@",json[@"CateID"]];
                NSDictionary *nDic = @{@"CateID":CateID,
                                       @"CateName":_textField.text,
                                       @"CateType":@"2"};
                
                MBSpaceMusicClassViewController *music = [[MBSpaceMusicClassViewController alloc]init];
                music.type = MusicClassType_Custom;
                music.dataDic = nDic;
                music.albumName = [[nDic objectForKey:@"CateName"]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [self.navigationController pushViewController:music animated:YES];
            } else {
                [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
            }
        } failure:^(NSError *error) {
            
        }];
    }
}

- (void)onSelectItemForBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onTapForHideAction
{
    [self.view endEditing:YES];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    int lengthCount = (int)(textField.text.length + string.length);
    if (lengthCount >= 21) {
        return NO;
    }
    _showLb.text = [NSString stringWithFormat:@"%d/20",lengthCount];
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    int lengthCount = (int)textField.text.length;
    if (lengthCount <= 21) {
        _showLb.text = [NSString stringWithFormat:@"%d/20",lengthCount];
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    int lengthCount = (int)textField.text.length;
    if (lengthCount <= 21) {
        _showLb.text = [NSString stringWithFormat:@"%d/20",lengthCount];
    }
}

@end
